package com.achieve.wx.exception;

import com.achieve.wx.domain.Result;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxMaErrorMsgEnum;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("系统异常", e);

        // 处理微信相关异常
        if (e instanceof WxErrorException) {
            WxErrorException wxError = (WxErrorException) e;
            if (WxMaErrorMsgEnum.CODE_40001.getCode() == wxError.getError().getErrorCode()) {
                // access_token无效
                return Result.fail("access_token无效，请重试");
            }
            return Result.fail("微信服务异常: " + wxError.getError().getErrorMsg());
        }

        return Result.fail("系统繁忙，请稍后再试");
    }
}
